﻿using ldc_mvc_closing_hwk.Models.Database;
using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ldc_mvc_closing_hwk.Controllers
{

    [Route("[controller]/[action]")]
    public class AdminxController : Controller
    {
        private readonly LdcFASContext _db;

        public AdminxController(LdcFASContext db)
        {
            _db = db;
        }

        [Route("/ArticleListManager")]
        [Route("/Admin")]
        public IActionResult ArticleListManager(string pwd)
        {
            if (pwd != "114514")
            {
                return new NotFoundResult();
            }
            return View();
        }

        [Route("/ArticleEdit.html")]
        public IActionResult ArticleEdit(int id)
        {
            var wwwrootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
            // 获取wwwroot/img目录下的所有文件
            var imageFiles = Directory.GetFiles(wwwrootPath + "/img");
            var relativePaths = imageFiles.Select(file => Path.GetFileName(file));

            // 将文件列表存储到ViewBag中
            ViewBag.ImageFiles = relativePaths;


            ViewBag.ArticleMeta = _db.ArticleMeta.Where(x => x.Id == id).First();

            ViewBag.ArticleContent = _db.ArticleContents.Where(x => x.FkArticleMeta == id).First();

            return View();
        }

        [Route("/ArticleCreate.html")]
        public IActionResult ArticleCreate()
        {
            var wwwrootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
            // 获取wwwroot/img目录下的所有文件
            var imageFiles = Directory.GetFiles(wwwrootPath + "/img");
            var relativePaths = imageFiles.Select(file => Path.GetFileName(file));

            // 将文件列表存储到ViewBag中
            ViewBag.ImageFiles = relativePaths;;

            ViewBag.ArticleAreas = _db.ArticleAreas.ToList();

            return View();
        }

        [Route("/article/edit")]
        public IActionResult ArticleEditPost()
        {
            var title = Request.Form["title"];
            var time = Request.Form["release_time"];
            var content = Request.Form["content"];
            var head_image = string.IsNullOrEmpty(Request.Form["head_image"]) ? null : ("~/img/" + Request.Form["head_image"]);
            var summary = Request.Form["summary"];
            var content_type = Request.Form["content_type"];
            var source_name = Request.Form["source_name"];

            _db.Database.ExecuteSqlRaw("SET XACT_ABORT ON");
            _db.Database.BeginTransaction();

            try
            {
                var articleMeta = new ArticleMetum
                {
                    CoverImage = head_image,
                    Title = title,
                    SourceName = source_name,
                    ReleaseTime = DateTime.Parse(time),
                    Summary = summary,
                    FkAreaId = 2
                };
                _db.Add(articleMeta);
                _db.SaveChanges();

                var lastInsertedId = articleMeta.Id;

                var articleContent = new ArticleContent
                {
                    ContentType = content_type,
                    Data = content,
                    FkArticleMeta = lastInsertedId
                };
                _db.Add(articleContent);
                _db.SaveChanges();

                _db.Database.CommitTransaction();
            }
            catch (Exception ex)
            {
                _db.Database.RollbackTransaction();

                TempData["Msg"] = "修改失败: " + ex.Message;
                return Redirect("/~ArticleCreate.html");
            }

            TempData["Msg"] = "修改成功!";
            return Redirect("~/ArticleCreate.html");
        }


        [HttpPost]
        [Route("/article/create")]
        public IActionResult ArticleCreatePost()
        {
            var title = Request.Form["title"];
            var time = Request.Form["release_time"];
            var content = Request.Form["content"];
            var article_area = 2;
            try
            {
                article_area = int.Parse(Request.Form["article_area"]);
            }
            catch { }
            var head_image = string.IsNullOrEmpty(Request.Form["head_image"]) ? null : ("~/img/" + Request.Form["head_image"]);
            var summary = Request.Form["summary"];
            var content_type = Request.Form["content_type"];
            var source_name = Request.Form["source_name"];

            _db.Database.ExecuteSqlRaw("SET XACT_ABORT ON");
            _db.Database.BeginTransaction();

            try
            {
                var articleMeta = new ArticleMetum
                {
                    CoverImage = head_image,
                    Title = title,
                    SourceName = source_name,
                    ReleaseTime = DateTime.Parse(time),
                    Summary = summary,
                    FkAreaId = article_area
                };
                _db.Add(articleMeta);
                _db.SaveChanges();

                var lastInsertedId = articleMeta.Id;

                var articleContent = new ArticleContent
                {
                    ContentType = content_type,
                    Data = content,
                    FkArticleMeta = lastInsertedId
                };
                _db.Add(articleContent);
                _db.SaveChanges();

                _db.Database.CommitTransaction();
            }
            catch (Exception ex)
            {
                _db.Database.RollbackTransaction();

                TempData["Msg"] = "创建失败: " + ex.Message;
                return Redirect("/~ArticleCreate.html");
            }

            TempData["Msg"] = "创建成功!";
            return Redirect("~/ArticleCreate.html");
        }
    }
}
